from typing import List


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        ret = 1000 * 1001
        for i_idx in range(0, len(nums) - 2):
            # close interval
            right = len(nums) - 1
            for left in range(i_idx + 1, len(nums) - 1):
                while right > left:
                    current_sum = nums[i_idx] + nums[left] + nums[right]
                    if current_sum > target:
                        if abs(current_sum - target) < abs(ret - target):
                            ret = current_sum
                        right -= 1
                    elif current_sum == target:
                        return target
                    else:
                        if abs(current_sum - target) < abs(ret - target):
                            ret = current_sum
                        break
        return ret